<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\GoldWaste;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Collection;

class ReturnGoldBeans extends Command
{
	protected $signature = 'cc:return-gold-beans';

	protected $description = "";

	public function handle()
	{
        User::where('gold_coins', '>', 0)->chunks(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
            foreach ($users as $user) {
                $user->goldCoins()->create([
                    'origin' => 0,
                    'result' => $user->gold_coins,
                    'money' => $user->gold_coins,
                    'remark' => 'init',
                    'reason' => '初始化',
                ]);
                Log::info("user: {$user->id} coins: {$user->gold_coins} initialized.");
            }

            return true;

        });

        User::where('gold_beans', '>', 0)->chunks(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
            foreach ($users as $user) {
                $user->goldBeans()->create([
                    'origin' => 0,
                    'result' => $user->gold_beans,
                    'money' => $user->gold_beans,
                    'remark' => 'init',
                    'reason' => '初始化',
                ]);
                Log::info("user: {$user->id} beans: {$user->gold_beans} initialized.");
            }

            return true;

        });

        User::chunks(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
            foreach ($users as $user) {

                $beans = $user->goldWastes()->sum('record_beans');

                if ($beans > 0) {
                    account_beans($user)->plusTransferedBeans($beans);
                }
                Log::info("user: {$user->id} beans: {$beans} returned.");
            }

            return true;
        });

		$this->info('Success.');
	}
}
